let layerIndex;
let $;
var toast;

/**
 * 弹出教师新增/编辑对话框
 * @param {number} id - 教师ID，有值表示编辑，无值表示新增
 */
function showTeacherDlg(id) {
    let title = "新增教师";
    if (id) {
        title = "编辑教师";
        $("#formId").css("display", "block");

        // 读取教师信息并填充表单
        $.ajax({
            url: "/api/teacher/" + id,
            method: "GET"
        }).done(result => {
            console.log(result);
            if(result.code >= 0) {
                // 填充表单数据
                $.each(result.data, function (key, value) {
                    var field = $('#teacherForm [name="' + key + '"]');
                    if (field.is(':radio')) {
                        field.filter('[value="' + value + '"]').prop('checked', true);
                    } else if (field.is(':checkbox')) {
                        field.prop('checked', value === "yes");
                    } else {
                        field.val(value);
                    }
                });
                layui.form.render();
            } else {
                toast.error({ message: result.msg });
            }
        });
    } else {
        $("#teacherForm")[0].reset();
        $("#formId").css("display", "none");
    }

    layerIndex = layer.open({
        type: 1,
        title: title,
        area: ['520px', 'auto'],
        content: $('#popDlg')[0].innerHTML
    });
}

/**
 * 获取查询条件
 */
function getTeacherSearchCondition() {
    let formData = {};
    $('#queryForm').find('input, select').each(function () {
        let name = $(this).attr('name');
        let value = $(this).val();
        if (name && value) {
            formData[name] = value;
        }
    });
    return formData;
}

/**
 * 加载教师列表
 */
function loadTeacherList() {
    const table = layui.table;
    let teacher = getTeacherSearchCondition();
    table.reloadData("tbTeacher", {
        where: { data: teacher }
    });
}

layui.use(['form', 'table', 'layer'], function () {
    $ = layui.$;
    toast = layui.toast;
    const form = layui.form;
    const table = layui.table;
    const layer = layui.layer;

    // 表单提交
    form.on('submit(teacher-dlg)', function (data) {
        event.preventDefault();
        if (this.isSubmitting) return false;
        this.isSubmitting = true;
        commitTeacherDlg()
            .catch(error => console.error('提交失败', error))
            .finally(() => this.isSubmitting = false);
        return false;
    });

    // 表格初始化
    table.render({
        elem: '#tbTeacher',
        url: '/api/teacher/getbypage',
        method: "POST",
        contentType: 'application/json',
        where: { data: getTeacherSearchCondition() },
        page: true,
        cols: [[
            { type: 'checkbox', fixed: 'left' },
            { field: 'id', fixed: 'left', width: 180, title: 'ID', sort: true },
            { field: 'no', title: '教职工号', width: 200 },
            { field: 'name', title: '姓名', width: 200 },
            {
                field: 'sex', title: '性别', width: 180,
                templet: d => d.sex === 1 ? '男' : (d.sex === 2 ? '女' : '未知')
            },
            { field: 'age', title: '年龄', width: 180, sort: true },
            { field: 'major', title: '专业' },

            // {
            //     fixed: 'right',
            //     title: '操作', templet: '#teacherEditTemplate'
            // }
        ]],
        done: function (rs) {
            if (rs.data.length === 0) layer.msg('没有找到相关数据');
        }
    });

    // 表格工具事件
    table.on('tool(tbTeacher)', function (obj) {
        if (obj.event === 'edit') {
            showTeacherDlg(obj.data.id);
        } else if (obj.event === 'delete') {
            deleteTeacherById(obj.data.id);
        }
    });
});

/**
 * 提交教师表单
 */
function commitTeacherDlg() {
    return new Promise((resolve, reject) => {
        $("#btnOK").prop("disabled", true).addClass("layui-btn-disabled");

        const id = $("#id").val();
        const formData = $(".layui-layer-page #teacherForm").serializeArray();
        const data = {};
        formData.forEach(item => {
            data[item.name] = item.value;
        });

        const url = id ? "/api/teacher/update" : "/api/teacher/add";
        const method = id ? "PUT" : "POST";

        $.ajax({
            url: url,
            method: method,
            contentType: 'application/json',
            data: JSON.stringify(data)
        }).done(result => {
            if (result.code === 0) {
                loadTeacherList();
                if (layerIndex) layer.close(layerIndex);
                layer.msg(id ? '更新成功' : '添加成功');
                resolve(result);
            } else {
                toast.error({ message: result.msg || (id ? "更新失败" : "添加失败") });
                reject(new Error(result.msg));
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            toast.error({ message: "系统错误，请稍后重试" });
            reject(new Error(`请求失败: ${textStatus} - ${errorThrown}`));
        }).always(() => {
            $("#btnOK").prop("disabled", false).removeClass("layui-btn-disabled");
        });
    });
}

/**
 * 批量删除确认
 */
function deleteTeacherConfirm() {
    const table = layui.table;
    const checkStatus = table.checkStatus('tbTeacher');

    if (checkStatus.data.length === 0) {
        layer.msg('请至少选择一条数据');
        return;
    }

    layer.confirm(`确定删除选中的${checkStatus.data.length}条数据吗？`, {icon: 3}, function(index) {
        const ids = checkStatus.data.map(item => item.id);
        $.ajax({
            url: "/api/teacher/deleteBatch",
            method: "POST",
            contentType: "application/json",
            data: JSON.stringify(ids)
        }).done(result => {
            if (result.code === 0) {
                layer.msg('删除成功');
                loadTeacherList();
            } else {
                layer.msg('删除失败: ' + result.msg);
            }
        }).fail(() => layer.msg('删除失败'));
        layer.close(index);
    });
}

/**
 * 单个删除
 */
function deleteTeacherById(id) {
    layer.confirm('确定删除该教师吗？', {icon: 3}, function() {
        $.ajax({
            url: "/api/teacher/delete/" + id,
            method: "DELETE"
        }).done(result => {
            if (result.code === 0) {
                layer.msg('删除成功');
                loadTeacherList();
            } else {
                layer.msg('删除失败: ' + result.msg);
            }
        }).fail(() => layer.msg('删除失败'));
    });
}

/**
 * 搜索教师
 */
function searchTeacher() {
    loadTeacherList();
}